package com.example.interceptor;

import com.example.service.impl.FlowServiceImpl;
import com.example.vo.IdHolder;
import com.example.vo.LoginUser;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @Description: 获取security实体里面的userId
 * @Author: aimi
 * @Create: 2024-05-17
 **/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class IdInterceptor implements HandlerInterceptor {

    private FlowServiceImpl flowService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Long userId = null;
        Long storeId = null;
        try {
            LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            userId = loginUser.getUser().getId();
            storeId = loginUser.getUser().getStoreId();
        } catch (Exception ignored) {

        }
        IdHolder.setUserId(userId);
        IdHolder.setStoreId(storeId);

        //统计访问流量
        String ip = request.getRemoteAddr();
        flowService.saveFlow(ip);
        return true;
    }
}